﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ARchGL.Declaration.Platform.Domain.Entities;
using ARchGL.Declaration.Platform.Service.Dtos;
using TDF.Core.Ioc;
using TDF.Core.Models;
using TDF.Data.Repository;

namespace ARchGL.Declaration.Platform.Service
{
    /// <summary>
    /// 数据推送服务
    /// </summary>
    public class PushService : BaseService, IPushService
    {
        ///获取推送数据-分页数据集合
        public Tuple<int, IPagedList<Push_Project_History>> GetPushPagedList(PushProjectHistoryCriteria criteria)
        {
            using (var repository = Ioc.Resolve<IRepositoryBase>())
            {
                var result = repository.IQueryable<Push_Project_History>()
                    .WhereByStatus(criteria.Status)
                    .WhereByKeywords(criteria?.Keywords?.Trim())
                    .WhereByType(criteria.Type)
                    .OrderByDescending(x => x.CreatedTime)
                    .ToPageResult1(criteria.PageIndex, criteria.PageSize);

                var count = repository.IQueryable<Push_Project_History>().WhereByStatus(PushStatus.失败).Count();

                return new Tuple<int, IPagedList<Push_Project_History>>(count, result);
            }
        }

        ///记录推送数据
        public void Save(Push_Project_History entity)
        {
            try
            {
                using (var repository = Ioc.Resolve<IRepositoryBase<Push_Project_History>>())
                {
                    entity.Id = Guid.NewGuid();
                    entity.CreatorName = string.Empty;
                    entity.CreatedTime = DateTime.Now;

                    entity.ModifierName = string.Empty;
                    repository.Insert(entity);
                }
            }
            catch
            {
                //阻止异常向上抛
            }
        }

        ///更新重试状态
        public void UpdateStatusById(Guid id)
        {
            using (var repository = Ioc.Resolve<IRepositoryBase<Push_Project_History>>())
            {
                var entity = repository.FindEntity(id);
                entity.Status = PushStatus.成功;
                entity.ModifiedTime = DateTime.Now;
                repository.Update(entity);
            }
        }

        ///更新重试状态
        public void UpdateStatus(List<Push_Project_History> list)
        {
            using (var repository = Ioc.Resolve<IRepositoryBase>().BeginTrans())
            {
                foreach (var item in list)
                {
                    item.ModifiedTime = DateTime.Now;
                    repository.Update(item);
                }
                repository.Commit();
            }
        }
    }
}
